package com.cmos.um.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;


import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


public class FileUtil {


    /**
     * 【工具】ftp下载文件
     *
     * @param ftp_ip     要下载文件的ftpip地址
     * @param ftp_path   要下载文件的ftp绝对路径
     * @param local_path 下载到本地的路径
     * @return
     */
    public static void fileDownloadByFtp(String ftp_ip, String ftp_path, String local_path, String ftpUserName, String ftpPassWord) {
        FTPClient ftpClient = new FTPClient();
        FileOutputStream fos = null;

        try {
            ftpClient.connect(ftp_ip);
            ftpClient.login(ftpUserName, ftpPassWord);
            //ftpClient.login("anonymous","1111");

            ftpClient.enterLocalActiveMode();

            String remoteFileName = ftp_path;

            fos = new FileOutputStream(local_path);
            ftpClient.setBufferSize(1024);
            // 设置文件类型（二进制）  
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.retrieveFile(remoteFileName, fos);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("FTP客户端出错！", e);
        } finally {
            IOUtils.closeQuietly(fos);
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("关闭FTP连接发生异常！", e);
            }
        }
    }

    /**
     * 【工具】读取txt文件的内容
     *
     * @param file 想要读取的文件对象
     * @return 返回文件中的内容
     */
    public static String txt2String(File file) {
        StringBuilder result = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));// 构造一个BufferedReader类来读取文件
            String s = null;
            String campaignid = null;

            for (int i = 0; i < 2; i++) {// 只读2行
                s = br.readLine();
                if (i == 1) {//只要第二行的
                    result.append(System.lineSeparator() + s);
                }
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    /**
     * 【工具】上传文件到media的/企业标识/outAddress/中
     *
     * @param in       想要读取的文件对象流
     * @param fileName 存储的文件名
     * @return 返回文件中的内容
     */
    public static boolean uploadFile(String uploadAddress, InputStream in, String fileName) throws IOException {

        //获取上传的HttpClient
        HttpClient client = new HttpClient();
        client.getParams().setAuthenticationPreemptive(true);

        PutMethod put = new PutMethod(uploadAddress);
        RequestEntity requestEntity = new InputStreamRequestEntity(in);
        put.setRequestEntity(requestEntity);
        client.executeMethod(put);
        System.out.println(put.getStatusCode());
        System.out.println("response: " + put.getStatusCode() + " " + put.getStatusText());
        return true;
    }


    /**
     * 从网络Url中下载文件
     * @param urlStr
     * @param fileName
     * @param savePath
     * @throws IOException
     */
    public static void  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3*1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);

        //文件保存位置
        File saveDir = new File(savePath);
        if(!saveDir.exists()){
            saveDir.mkdir();
        }
        File file = new File(saveDir+File.separator+fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if(fos!=null){
            fos.close();
        }
        if(inputStream!=null){
            inputStream.close();
        }


        System.out.println("info:"+url+" download success");

    }

    /**
     * 从输入流中获取字节数组
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    public static void main(String[] args) {
        try{
            downLoadFromUrl("http://e.hiphotos.baidu.com/image/pic/item/5366d0160924ab1833f8e6fd3cfae6cd7a890b09.jpg",
                    "百度.jpg","/home/maqingsong/");
        }catch (Exception e) {
            // TODO: handle exception
        }
    }


//    public static void main(String[] args) throws IOException {
//        HttpClient client = new HttpClient();
//        client.getParams().setAuthenticationPreemptive(true);
//
////		String fileName = file.getOriginalFilename();
////		String uploadFileUrl = path.endsWith("/") ? path + fileName : path + "/" + fileName;
//
//        PutMethod put = new PutMethod("http://127.0.0.1/q1.txt");
//        InputStream in = new FileInputStream("/home/maqingsong/ftp/q1.txt");
//        RequestEntity requestEntity = new InputStreamRequestEntity(in);
//        put.setRequestEntity(requestEntity);
//        client.executeMethod(put);
//        System.out.println(put.getStatusCode());
//        System.out.println("response: " + put.getStatusCode() + " " + put.getStatusText());
//    }
}
